#pragma once
#include<iostream>
#include <sys/epoll.h>
#include "Log.hpp"
#include "Common.hpp"


using namespace LogModule;
class Epoller
{
public:
    Epoller()
    {
        //创建一个epoll模型
        _epfd = epoll_create(256);//参数其实无关,当代内核已将其忽略
        if(_epfd < 0)
        {
            //模型创建失败还玩什么,打印日志退出吧
            LOG(LogLevel::FATAL) << "epoll_create error";
            exit(EPOLL_CREATE_ERR);
        }
            LOG(LogLevel::FATAL) << "epoll_create success: " << _epfd;

    }

    void EventHelper(int sockfd, uint32_t event, int oper)
    {
        epoll_event events;
        events.events = event;//关心事件写入到内核结构体
        events.data.fd = sockfd;//细节(算是一个回指文件描述符)
        int n = epoll_ctl(_epfd, oper, sockfd, &events);
        if(n < 0)
        {
            LOG(LogLevel::WARNING) << "epoll_ctl error";
            return;
        }
        LOG(LogLevel::WARNING) << "epoll_ctl success";
    }
    void AddEvent(uint32_t event, int fd)
    {
        EventHelper(fd, event, EPOLL_CTL_ADD);
    }

    void ModEvent(int sockfd, uint32_t& event)
    {
        EventHelper(sockfd, event, EPOLL_CTL_MOD);
    }

    void DelEvent(int sockfd)
    {
        int n = epoll_ctl(_epfd, EPOLL_CTL_DEL, sockfd, nullptr);
    }
    int WaitEvents(struct epoll_event* events, int size, int timeout)
    {
        int n =  epoll_wait(_epfd, events, size, timeout);
        if(n < 0)
        {
            //等待失败
            LOG(LogLevel::WARNING) << "epoll_wait error";
        }
        else if(n == 0)
        {
            //等待超时
            LOG(LogLevel::WARNING) << "epoll_wait timeout...";
        }
        else
        {
            //等待成功
            //LOG(LogLevel::WARNING) << "epoll_wait success";
        }
        return n;
    }

    
    ~Epoller()
    {

    }
private:
    int _epfd;
};